package com.qianyu.core.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianyu.core.entity.base.PageDTO;
import com.qianyu.core.entity.bean.QqAccount;
import com.qianyu.core.entity.bean.QqRecycleOrder;
import com.qianyu.core.entity.bean.User;
import com.qianyu.core.entity.dto.QqRecycleOrderDto;
import com.qianyu.core.enumerate.ResultEnum;
import com.qianyu.core.exception.CustomerException;
import com.qianyu.core.helper.LoginHelper;
import com.qianyu.core.mapper.QqRecycleOrderMapper;
import com.qianyu.core.service.QqAccountService;
import com.qianyu.core.service.QqRecycleOrderService;
import com.qianyu.core.service.UserService;
import com.qianyu.core.util.TimeUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class QqRecycleOrderServiceImpl extends ServiceImpl<QqRecycleOrderMapper, QqRecycleOrder> implements QqRecycleOrderService {

    private final UserService userService;

    private final QqAccountService qqAccountService;

    /**
     * 新增回收单
     *
     * @param dto
     * @return
     */
    @Override
    public boolean saveQqRecycleOrder(QqRecycleOrderDto.QqRecycleOrderSaveDto dto) {
        Collection<QqAccount> accounts = qqAccountService.listByIds(dto.getAccountIds());
        BigDecimal nowQNum = accounts.stream().map(QqAccount::getQnum).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal originQnum = accounts.stream().map(QqAccount::getOriginQnum).reduce(BigDecimal.ZERO, BigDecimal::add);
        List<String> list = accounts.stream().map(QqAccount::getQq).collect(Collectors.toList());
        validateOrder(list);
        QqRecycleOrder order = new QqRecycleOrder() {{
            setUserId(LoginHelper.getUserId());
            setAgencyId(userService.getById(LoginHelper.getUserId()).getAgencyId());
            setSn("RCON" + TimeUtil.unixTime());
            setNum(accounts.size());
            setNowQnum(nowQNum);
            setOriginQnum(originQnum);
            setRateUsdt(dto.getRateUsdt());
            setQqAccounts(StringUtils.strip(StringUtils.strip(list.toString(), "["), "]"));
        }};
        return save(order);
    }

    private void validateOrder(List<String> list) {
        LambdaQueryWrapper<QqRecycleOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(QqRecycleOrder::getUserId,LoginHelper.getUserId())
                .like(QqRecycleOrder::getQqAccounts,StringUtils.strip(StringUtils.strip(list.toString(), "["), "]"));
        if(ObjectUtil.isNotEmpty(list(wrapper))){
            throw new CustomerException(ResultEnum.ACCOUNT_IS_IN_ORDER);
        }
    }

    /**
     * @param dto
     * @param type 0-管理审核查询 1-代理商查询 2-用户查询
     * @return
     */
    @Override
    public Page<QqRecycleOrder> pageList(PageDTO dto, Integer type) {
        Map<Long, String> map = userService.list().stream().collect(Collectors.toMap(User::getId, User::getNickname));
        Page<QqRecycleOrder> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<QqRecycleOrder> wrapper = Wrappers.lambdaQuery();
        if (type == 1) {
            wrapper.eq(QqRecycleOrder::getAgencyId, LoginHelper.getUserId());
        } else if (type == 2) {
            wrapper.eq(QqRecycleOrder::getUserId, LoginHelper.getUserId());
        }
        IPage<QqRecycleOrder> orderIPage = page(page, wrapper);
        orderIPage.getRecords().forEach(o -> {
            o.setAgencyName(map.get(o.getAgencyId()));
            o.setNickname(map.get(o.getUserId()));
        });
        return (Page<QqRecycleOrder>) orderIPage;
    }

    /**
     * 审核回收单
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean checkRecycleOrder(QqRecycleOrderDto.QqRecycleOrderCheckDto dto) {

        if (dto.getStatus() > 2 || dto.getStatus() < 1) {
            throw new CustomerException(ResultEnum.USER_REQUEST_PARAMETER_ERROR);
        }

        User user = LoginHelper.getLoginUser();
        QqRecycleOrder order = getById(dto.getId());
        //代理商审核
        if (user.getRole() == 1) {
            order.setAgencyAuditTime(TimeUtil.unixTime());
            order.setAgencyAuditText(dto.getAuditText());
            order.setStatus(dto.getStatus());
        } else {
            if(order.getAgencyAuditTime() == null || order.getAgencyAuditTime() == 0){
                throw new CustomerException(ResultEnum.WAIT_AGENCY_AUDIT);
            }
            order.setAdminAuditTime(TimeUtil.unixTime());
            order.setAdminAuditText(dto.getAuditText());
            if (dto.getStatus() == 1) {
                order.setStatus(3);
            } else {
                order.setStatus(4);
                String[] accounts = order.getQqAccounts().split(",");
                qqAccountService.update(Wrappers.<QqAccount>lambdaUpdate().set(QqAccount::getRecoveryStatus, 1).in(QqAccount::getQq, accounts));
            }

        }
        return updateById(order);
    }
}
